//
//  GTSearchViewController.m
//  GiftTalk
//
//  Created by Wan on 16/3/25.
//  Copyright © 2016年 Wan. All rights reserved.
//  搜索控制器

#import "GTSearchViewController.h"
#import <UICollectionViewLeftAlignedLayout.h>
#import "GTHotWordsCollectionViewCell.h"
#import "GTHotWordsHeaderView.h"
#import "GTHotWordsFooterView.h"
#import <AFNetworking.h>
#import "GTSaveTool.h"
#import "GTChannelViewController.h"
#import "GTGiftItemViewController.h"
#import "GTSearchResultSegment.h"

static const CGFloat GTHotWordReuseHeaderH = 35;            // 可重用 headerView 的高度
static const CGFloat GTHotWordsCollectionMargin = 10;       // 间距
static const CGFloat GTHotWordsCellHorizontalMargin = 15;   // Cell 行间距
static const CGFloat GTHotWordsCellVerticalMargin = 8;      // Cell 列间距
static const CGFloat GTResultSegementH = 44;                // 搜索结果页 Segement 高度

static NSString * const reuseItemIdentifier = @"hotWordItem";
static NSString * const reuseHeaderIdentifier = @"hotWordHeader";
static NSString * const reuseFooterIdentifier = @"hotWordFooter";

@interface GTSearchViewController() <UISearchBarDelegate, UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
/** 热词容器 */
@property (weak, nonatomic) IBOutlet UICollectionView *hotWordsCollectionView;
/** 热词容器底部约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hotWordsCollectionToViewBottomConstraint;
/** 搜索结果视图 */
@property (weak, nonatomic) IBOutlet UIView *resultContainerView;
@property (weak, nonatomic) GTSearchResultSegment *resultSegement;
@property (weak, nonatomic) UISearchBar *searchBar;
@property (weak, nonatomic) UIView *guideResultView;
@property (weak, nonatomic) UIView *giftResultView;

@property (strong, nonatomic) NSArray *hotWords;
@property (strong, nonatomic) NSMutableArray *searchHistory;
@property (strong, nonatomic) NSMutableArray *collectionDataArray;
/** 请求管理者 */
@property (strong, nonatomic) AFHTTPSessionManager *manager;


@end

@implementation GTSearchViewController

#pragma mark - 懒加载
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (NSMutableArray *)searchHistory
{
    if (_searchHistory == nil) {
//        _searchHistory = @[].mutableCopy;
        _searchHistory = [NSMutableArray array];
    }
    return _searchHistory;
}

- (NSMutableArray *)collectionDataArray
{
    if (_collectionDataArray == nil) {
//        _collectionDataArray = @[].mutableCopy;
        _collectionDataArray = [NSMutableArray array];
        if (self.searchHistory.count) {
            [_collectionDataArray addObject:self.searchHistory];
        }
    }
    
//    GTLog(@"%ld",self.collectionDataArray.count);
    
    return _collectionDataArray;
}

- (GTSearchResultSegment *)resultSegement
{
    if (!_resultSegement) {
        GTSearchResultSegment *resultSegement = [GTSearchResultSegment segment];
        
        resultSegement.leftTitle = @"礼物";
        resultSegement.rightTitle = @"攻略";
        resultSegement.frame = CGRectMake(0, 0, GTScreenW, GTResultSegementH);
        [resultSegement leftButtonAddTarget:self selector:@selector(giftButtonOnClick) forContrlEvents:UIControlEventTouchUpInside];
        [resultSegement rightButtonAddTarget:self selecror:@selector(guideButtonOnClick) forContrlEvents:UIControlEventTouchUpInside];
        
        [self.resultContainerView addSubview:resultSegement];
        _resultSegement = resultSegement;
    }
    return _resultSegement;
}

#pragma mark - 初始化
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    GTLogFunc
    // 1. 初始化导航栏
    [self setupNav];
    // 2. 初始化搜索框控件
    [self setupSearchBar];
    // 3. 初始化热词推荐
    [self setupHotWordsCollectionView];
    // 4. 加载热词
    [self loadHotWordsData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    CGRect keyboardFrame = [notification.userInfo[@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue];
    
    self.hotWordsCollectionToViewBottomConstraint.constant = keyboardFrame.size.height;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 界面即将显示就获取沙盒中的搜索记录
    [self.searchHistory addObjectsFromArray:[GTSaveTool objectForKey:GTSaveKeySearchHistory]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.searchBar endEditing:YES];
}

/**
 *  初始化导航栏
 */
- (void)setupNav
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = GTBackgroundColor;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style: UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    // 用于覆盖统一设置的返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:nil];
    
    // 这句代码可以重现导航栏返回按钮
//    self.navigationItem.leftBarButtonItem = nil;
}

/**
 *  初始化搜索框控件
 */
- (void)setupSearchBar
{
    // 从中间开始，向左偏移半个屏幕长度左右
    CGFloat navigationBar_height = self.navigationController.navigationBar.height;
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, navigationBar_height)];
    
    CGFloat searchX = - GTScreenW / 2 + 10;
    CGFloat searchW = GTScreenW - 59;
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(searchX, 0, searchW, containerView.height)];
    searchBar.placeholder = @"搜索礼物、攻略";
    searchBar.delegate = self;
    [searchBar setTintColor:[UIColor blueColor]];
    [searchBar becomeFirstResponder];
    
    [containerView addSubview:searchBar];
    self.navigationItem.titleView = containerView;
    self.searchBar = searchBar;
    
    // 移除 搜索框控件的背景色
    for (UIView *subView in searchBar.subviews) {
        if ([subView isKindOfClass:[UIView class]] && subView.subviews.count > 0) {
            [[subView.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
    }
}

/**
 *  初始化热词推荐
 */
- (void)setupHotWordsCollectionView
{
    UICollectionViewLeftAlignedLayout *layout = [[UICollectionViewLeftAlignedLayout alloc] init];
//    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = GTHotWordsCollectionMargin;
    layout.minimumInteritemSpacing = GTHotWordsCollectionMargin;
    layout.headerReferenceSize = CGSizeMake(GTScreenW, GTHotWordReuseHeaderH);
    
    self.hotWordsCollectionView.collectionViewLayout = layout;
    self.hotWordsCollectionView.backgroundColor = GTRGBColor(249, 249, 249);
    self.hotWordsCollectionView.contentInset = UIEdgeInsetsMake(0, GTHotWordsCollectionMargin, GTHotWordReuseHeaderH, GTHotWordsCollectionMargin);
    self.hotWordsCollectionView.delegate = self;
    self.hotWordsCollectionView.dataSource = self;
    self.hotWordsCollectionView.allowsMultipleSelection = NO;   //默认为NO,是否可以多选
    
    /** 注册 collectionView & collectionViewCell */
    // 通过Class 注册生成cell，viewCell需要继承 UICollectionViewCell
    [self.hotWordsCollectionView registerClass:[GTHotWordsCollectionViewCell class] forCellWithReuseIdentifier:reuseItemIdentifier];
    
    //注册headerView, Nib的view需要继承UICollectionReusableView
    [self.hotWordsCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GTHotWordsHeaderView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reuseHeaderIdentifier];
    //注册footerView, Nib的view需要继承UICollectionReusableView
    [self.hotWordsCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GTHotWordsFooterView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:reuseFooterIdentifier];
    self.resultContainerView.hidden = YES;
}

/**
 *  加载热词
 */
- (void)loadHotWordsData
{
    [self.manager GET:@"http://api.liwushuo.com/v2/search/hot_words?" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.hotWords = responseObject[@"data"][@"hot_words"];
        // 加载完成，插入到首个位置
        [self.collectionDataArray insertObject:self.hotWords atIndex:0];
        self.searchBar.placeholder = responseObject[@"data"][@"placeholder"];
        [self.hotWordsCollectionView reloadData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        GTLog(@"%@",error);
    }];
}

/**
 *  设置搜索结果- 攻略视图
 */
- (void)setupGuidResultViewWithHotWord:(NSString *)hotWord
{
    NSString *sortStr = [hotWord stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    GTChannelViewController *channelVc = [[GTChannelViewController alloc] init];
    channelVc.dataArrayName = @"posts";
    channelVc.firstPageURLString = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/post?keyword=%@&limit=20&offset=0&sort=",sortStr];
        
    CGFloat width = self.resultContainerView.width;
    CGFloat height = self.resultContainerView.height - GTResultSegementH;
    channelVc.view.frame = CGRectMake(0, GTResultSegementH, width, height);
    
    [self addChildViewController:channelVc];
    [self.resultContainerView addSubview:channelVc.view];
    
    self.guideResultView = channelVc.view;
    
}

/**
 *  设置搜索结果- 礼物视图
 */
- (void)setupGiftResultViewWithHotWord:(NSString *)hotWord
{
    GTGiftItemViewController *giftItemVc = [[GTGiftItemViewController alloc] init];
    
    NSString *sortStr = [hotWord stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    giftItemVc.firstPageURLString = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item?keyword=%@&limit=20&offset=0&sort=", sortStr];
    CGFloat width = self.resultContainerView.width;
    CGFloat height = self.resultContainerView.height - GTResultSegementH;
    giftItemVc.view.frame = CGRectMake(0, GTResultSegementH, width, height);
    
    [self addChildViewController:giftItemVc];
    [self.resultContainerView addSubview:giftItemVc.view];
    
    self.giftResultView = giftItemVc.view;
    
}

/**
 *  根据热词返回搜索结果
 *
 *  @param hotWord 搜索关键字
 */
- (void)searchWithHotWord:(NSString *)hotWord
{
    self.searchBar.text = hotWord;
    
    // 这句代码可以重现导航栏返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:nil];
    
    // 存储搜索记录
    if (![self.searchHistory containsObject:hotWord]) {
        [self.searchHistory addObject:hotWord];
        [GTSaveTool setObject:self.searchHistory forKey:GTSaveKeySearchHistory];
    }
    
    // 礼物－攻略segment
    [self resultSegement];
    
    // 添加搜索结果view
    [self setupGuidResultViewWithHotWord:hotWord];
    [self setupGiftResultViewWithHotWord:hotWord];
    self.guideResultView.hidden = YES;
    self.giftResultView.hidden = NO;
    self.resultContainerView.hidden = NO;
    
    // 关闭键盘
    [self.searchBar endEditing:YES];
}

#pragma mark - <UISearchBarDelegate>
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 根据关键词查找数据
    [self searchWithHotWord:searchBar.text];
}

#pragma mark - <UICollectionViewDataSource>

/**
 *  Section 的个数
 */
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.collectionDataArray.count;
}

/**
 *  每个 Section 展示的 item 的个数
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.collectionDataArray[section] count];
}

/**
 *  设置每个 cell 的数据
 */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GTHotWordsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseItemIdentifier forIndexPath:indexPath];
    
    cell.title = self.collectionDataArray[indexPath.section][indexPath.item];
    
    return cell;
}

/**
 *  设置头部/尾部 视图的文字
 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *reusableView = nil;
    
    if (kind == UICollectionElementKindSectionHeader) {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reuseHeaderIdentifier forIndexPath:indexPath];
        // 根据组别设置 头部视图的名称
        ((GTHotWordsHeaderView *)reusableView).title = indexPath.section == 0 ? @"大家都在搜" : @"搜索历史";
        
//        GTLog(@"%ld - %@ - %@",indexPath.section, ((GTHotWordsHeaderView *)reusableView).title, NSStringFromCGRect(reusableView.frame));
    } else {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:reuseFooterIdentifier forIndexPath:indexPath];
        // 清除历史搜索记录
        [(GTHotWordsFooterView *)reusableView addTarget:self action:@selector(clearSearchHistory) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return reusableView;
    
}

#pragma mark - <UICollectionViewDelegateFlowLayout>
/**
 *  定义每个 item 的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = indexPath.section == 0 ? self.hotWords[indexPath.item] : self.searchHistory[indexPath.item];
    NSDictionary *textAttrs = @{NSFontAttributeName: GTHotWordsFont};

    // 根据文字内容计算 cell 的 frame
    CGRect rect = [title boundingRectWithSize:CGSizeMake(GTScreenW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:textAttrs context:nil];
    CGFloat itemW = rect.size.width + GTHotWordsCellHorizontalMargin * 2;
    CGFloat itemH = rect.size.height + GTHotWordsCellVerticalMargin * 2;
    
    return CGSizeMake(itemW, itemH);
}

/**
 *  定义每个 footerView 的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (section == self.collectionDataArray.count - 1
        && [self.collectionDataArray lastObject] == self.searchHistory) {
        return CGSizeMake(GTScreenW, GTHotWordReuseHeaderH);
    }
    
    return CGSizeZero;
}


#pragma mark - <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *hotWord = indexPath.section == 0 ? self.hotWords[indexPath.row] : self.searchHistory[indexPath.row];
    
    // 根据关键词查找数据
    [self searchWithHotWord:hotWord];
}

#pragma mark - 监听回调
- (void)giftButtonOnClick
{
    self.giftResultView.hidden = NO;
    self.guideResultView.hidden = YES;
}

- (void)guideButtonOnClick
{
    self.giftResultView.hidden = YES;
    self.guideResultView.hidden = NO;
}

- (void)clearSearchHistory
{
    [self.collectionDataArray removeObject:self.searchHistory];
    self.searchHistory = nil;
    [GTSaveTool setObject:self.searchHistory forKey:GTSaveKeySearchHistory];
    [self.hotWordsCollectionView reloadData];
}

- (void)cancel
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
